package com.example.badminton.controller;

import com.example.badminton.common.AnonymousAccess;
import com.example.badminton.common.Result;
import com.example.badminton.entity.News;
import com.example.badminton.service.NewsService;
import com.example.badminton.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/news")
@CrossOrigin
public class NewsController {

    @Autowired
    private NewsService newsService;

    @AnonymousAccess
    @GetMapping("/list")
    public Result<List<News>> getNewsList(
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword) {
        List<News> newsList = newsService.getNewsList(category, keyword);
        return Result.success(newsList);
    }

    @AnonymousAccess
    @GetMapping("/{id}")
    public Result<News> getNewsById(@PathVariable Long id) {
        News news = newsService.getById(id);
        if (news == null) {
            return Result.error("资讯不存在");
        }
        return Result.success(news);
    }

    @PostMapping("/like/{id}")
    public Result<String> likeNews(@PathVariable Long id) {
        Long userId = UserUtils.getCurrentUserId();
        
        // 这里可以添加点赞逻辑
        // 例如：检查用户是否已经点赞过，更新点赞数等
        return Result.success("点赞成功");
    }

    @PostMapping("/create")
    public Result<News> createNews(@RequestBody News news) {
        // 检查管理员权限
        if (!UserUtils.isAdmin()) {
            return Result.error("无权限创建资讯");
        }
        
        newsService.save(news);
        return Result.success(news);
    }

    @PutMapping("/{id}")
    public Result<News> updateNews(@PathVariable Long id, @RequestBody News news) {
        // 检查管理员权限
        if (!UserUtils.isAdmin()) {
            return Result.error("无权限修改资讯");
        }
        
        news.setId(id);
        newsService.updateById(news);
        return Result.success(news);
    }

    @DeleteMapping("/{id}")
    public Result<String> deleteNews(@PathVariable Long id) {
        // 检查管理员权限
        if (!UserUtils.isAdmin()) {
            return Result.error("无权限删除资讯");
        }
        
        newsService.removeById(id);
        return Result.success("删除成功");
    }
} 